﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Linq;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using Dropthings.Widget.Framework;
using Dropthings.Widget.Widgets;
using Dropthings.Widget.Widgets.FusionCharts;
using InfoSoftGlobal;
using Dropthings.Util;
using Dropthings.Business.Facade;
using Dropthings.Business.Facade.Context;
using System.Collections.Generic;
using System.Text;

public partial class FusionChart_PropertyAmmeter : System.Web.UI.UserControl, IWidget
{
    #region Fields

    private IWidgetHost _Host;
    private XElement _State;
    private XElement State
    {
        get
        {
            if (_State == null)
            {
                string stateXml = this._Host.GetState();
                if (string.IsNullOrEmpty(stateXml))
                {
                    _State = new XElement("state",
                        new XElement("year", DateTime.Now.Year.ToString()));
                }
                else
                {
                    _State = XElement.Parse(stateXml);
                }
            }
            return _State;
        }
    }

    public int ShowYear
    {
        get { return State.Element("year") == null ? DateTime.Now.Year : int.Parse(State.Element("year").Value); }
        set
        {
            if (State.Element("year") == null)
                State.Add(new XElement("year", value));
            else
                State.Element("year").Value = value.ToString();
        }
    }

    private string panelId;

    public string PanelId
    {
        get { return "Panle_" + _Host.WidgetInstance.Id; }
        set { panelId = value; }
    }
    

    private string _chartSwfUrl = "";
    private StringBuilder _charXmlData = new StringBuilder();

    #endregion Fields

    #region IWidget接口实现
    void IEventListener.AcceptEvent(object sender, EventArgs e)
    {
        
    }

    void IWidget.Closed()
    {
    }

    void IWidget.Collasped()
    {
    }

    void IWidget.Expanded()
    {
    }

    void IWidget.HideSettings(bool userClicked)
    {
        SettingsPanel.Visible = false;
        if (userClicked)
        {
            this.ShowYear = int.Parse(YearDropDownList.SelectedValue);
            this.SaveState();
            if (yearlbl.Text != ShowYear.ToString())
            {
                if (lbtnBack.Visible)
                    CreateYearChartByProperty(typelbl.Text);
                else
                    CreateYearChart();
            }
            yearlbl.Text = ShowYear.ToString();
        }
    }

    void IWidget.Init(IWidgetHost host)
    {
        this._Host = host;
    }

    void IWidget.Maximized()
    {
    }

    void IWidget.Restored()
    {
    }

    void IWidget.ShowSettings(bool userClicked)
    {
        SettingsPanel.Visible = true;
        if (userClicked)
        {
            YearDropDownList.SelectedIndex = -1;
            YearDropDownList.Items.FindByText(this.ShowYear.ToString()).Selected = true;
        }
    }
    #endregion

    #region 页面事件处理
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (YearDropDownList.Items.Count == 0)
        {
            for (int i = 2000; i <= DateTime.Now.Year; i++)
            {
                YearDropDownList.Items.Add(new ListItem(i.ToString()));
            }
        }
        if (!ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
        {
            yearlbl.Text = this.ShowYear.ToString();
            CreateYearChart();
        }
        else
        {
            String sEventArguments = Request["__EVENTARGUMENT"];
            if (sEventArguments != null)
            {
                //extract arguments passed to the HTTP Request  
                Int32 iDelimiter = sEventArguments.IndexOf('$');
                String sArgument = sEventArguments.Substring(iDelimiter + 1);
                // extract the name of the post back function 
                if (sEventArguments.StartsWith(this._Host.ID.ToString()))
                {
                    // call the post back function passing the argument(s)
                    CreateYearChartByProperty(sArgument);
                }
                else
                {
                    if (string.IsNullOrEmpty(Literal1.Text))
                        CreateYearChart();
                }
            }
        }
    }

    protected void SaveSettings_Click(object sender, EventArgs e)
    {
        _Host.HideSettings(true);
    }

    protected void lbtnBack_Click(object sender, EventArgs e)
    {
        lbtnBack.Visible = false;
        CreateYearChart();
    }
    
    #endregion

    #region 页面处理方法
    private void ShowChart()
    {
         Literal1.Text = FusionCharts.RenderChartHTML(_chartSwfUrl, "", _charXmlData.ToString(), "myFirst", "100%", "267", false, false);
         _Host.Refresh(this);
    }

    private void SaveState()
    {
        var xml = this.State.Xml();
        this._Host.SaveState(xml);
        this._State = null;
    }

    private void CreateYearChart()
    {
        _charXmlData = new StringBuilder();
        _chartSwfUrl = "../FusionCharts/Pie3D.swf";
        _charXmlData.AppendFormat("<chart caption='各行业电能年耗图 - {0}' unescapeLinks='0' animation='1' baseFontColor='FFFFFF' bgColor='2E4A89, 90B1DE' pieYScale='30'  pieSliceDepth='8' smartLineColor='FFFFFF'>", ShowYear);
        DataSet datasDS = getYearDatasGroupbyProperty(ShowYear);

        if (datasDS != null && datasDS.Tables.Count > 0 && datasDS.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow dr in datasDS.Tables[0].Rows)
            {
                string OrgPropertyName = Convert.ToString(dr["OrgPropertyName"]);
                string OrgPropertyCode = Convert.ToString(dr["OrgPropertyCode"]);
                double MonthData=Convert.ToDouble(dr["MonthData"]);
                _charXmlData.AppendFormat("<set value='{0}' label='{1}' link='JavaScript:updateChart(%26quot;{2}%26quot;,%26quot;{3}%26quot;)' />", MonthData, OrgPropertyName, this._Host.ID, OrgPropertyCode);
            }
        }

        _charXmlData.Append("<styles>");
        _charXmlData.Append("<definition>");
        _charXmlData.Append("<style name='CaptionFont' type='FONT' size='12' bold='1' />");
        _charXmlData.Append("<style name='LabelFont' type='FONT' color='2E4A89' bgColor='FFFFFF' bold='1' />");
        _charXmlData.Append("<style name='ToolTipFont' type='FONT' bgColor='2E4A89' borderColor='2E4A89' />");
        _charXmlData.Append("</definition>");
        _charXmlData.Append("<application>");
        _charXmlData.Append("<apply toObject='CAPTION' styles='CaptionFont' />");
        _charXmlData.Append("<apply toObject='DATALABELS' styles='LabelFont' />");
        _charXmlData.Append("<apply toObject='TOOLTIP' styles='ToolTIpFont' />");
        _charXmlData.Append("</application>");
        _charXmlData.Append("</styles>");
        _charXmlData.Append("</chart>");
        ShowChart();
    }

    private void CreateYearChartByProperty(string propertyCode)
    {
         lbtnBack.Visible = true;
         typelbl.Text = propertyCode;
        _charXmlData = new StringBuilder();
        _chartSwfUrl = "../FusionCharts/StackedColumn2D.swf";
        _charXmlData.AppendFormat("<chart caption='{0}行业电能月耗图- {1}' xAxisName='建筑' yAxisName='千瓦时' showNames='1' ", getOrganizePorpertyName(propertyCode), ShowYear);
        _charXmlData.Append("animation='1' baseFontColor='666666' useRoundEdges='1'>");
        DataSet ammeterItemInfoDS = getAmmeterItemInfo();
        DataSet datasDS = getYearDatasByProperty(ShowYear, propertyCode);
        DataTable dt = null;
        if (datasDS != null && datasDS.Tables.Count > 0)
        {
            dt = datasDS.Tables[0];
            if (dt != null)
            {
                _charXmlData.Append("<categories>");
                var queryBuildings = from o in dt.AsEnumerable()
                                     group o by new  {  
                                         OrganizeName=o.Field<string>("OrganizeName"),
                                         OrganizeIdentify=o.Field<string>("OrganizeIdentify")  
                                     }into g
                                     select new { g.Key, num = g.Count() };
                if (queryBuildings != null)
                {
                    foreach (var building in queryBuildings)
                    {
                        _charXmlData.AppendFormat("<category label='{0}' />", building.Key.OrganizeName);
                    }
                }
                _charXmlData.Append("</categories>");
                if (ammeterItemInfoDS != null && ammeterItemInfoDS.Tables.Count > 0 && ammeterItemInfoDS.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in ammeterItemInfoDS.Tables[0].Rows)
                    {
                        string EnergyItemNo = dr["EnergyItemNo"].ToString();
                        _charXmlData.AppendFormat("<dataset seriesName='{0}' >", dr["EnergyItemName"].ToString());
                        var query = from o in dt.AsEnumerable()
                                    where o.Field<string>("EnergyItemNo") == EnergyItemNo
                                    orderby o.Field<string>("OrganizeIdentify")
                                    select o;
                        foreach (var building in queryBuildings)
                        {
                            string strData = "<set value='' />";
                            if (query != null)
                            {
                                foreach (var dataDr in query)
                                {
                                    if (dataDr.Field<string>("OrganizeIdentify") == building.Key.OrganizeIdentify)
                                    {
                                        strData = string.Format("<set value='{0}' />", dataDr.Field<decimal>("MonthData"));
                                        break;
                                    }
                                }
                            }
                            _charXmlData.Append(strData);
                        }
                        _charXmlData.Append("</dataset>");
                    }
                }
            }
        }              
        _charXmlData.Append("</chart>");
        ShowChart();
    }

   
    #endregion

    private Dictionary<string, string> getAllBuildings()
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            Dictionary<string, string> allBuildings = new Dictionary<string, string>();
            DataSet ds = facade.GetOrganizeBaseInfo();
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string name = Convert.ToString(dr["OrganizeName"]);
                    string key = Convert.ToString(dr["OrganizeIdentify"]);
                    allBuildings.Add(key, name);
                }
            }
            return allBuildings;
        }
    }

    private string getOrganizePorpertyName(string propertyCode)
    {
        string PorpertyName = string.Empty;
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            DataSet ds = facade.GetOrganizePeropertyInfo(propertyCode);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                PorpertyName = ds.Tables[0].Rows[0]["OrgPropertyName"].ToString();
            }
        }
        return PorpertyName;
    }

    private DataSet getAmmeterItemInfo()
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            DataSet ds = facade.GetAmmeterItemInfo();
            return ds;
        }
    }

    private DataSet getYearDatasGroupbyProperty(int year)
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            DataSet ds = facade.GetAmmeterYearDatasGroupbyProperty(year);
            return ds;
        }
    }

    private DataSet getYearDatasByProperty(int year, string propertyCode)
    {
        using (Facade facade = new Facade(AppContext.GetContext(Context)))
        {
            DataSet ds = facade.GetAmmeterYearDatasByProperty(year, propertyCode);
            return ds;
        }
    }
}